/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useMemo, useRef, useState } from 'react';
import { fixStyles, useIframeHeight, getOldRoute } from './_utils/';
import { useLocation, useModel } from 'umi';
import type { Location } from 'umi';
import qs from 'qs';
import classNames from 'classnames';
import { Spin } from 'antd';
import styles from './index.less';

interface IframeProps {
  pathname?: string;
  src?: string;
}

const Iframe: React.FC<IframeProps> = (props) => {
  const location: Location = useLocation();
  const { initialState } = useModel('@@initialState');
  const [show, setShow] = useState(false);
  const { winSize } = initialState || {};
  const { pathname: locationPathname, query, hash } = location;
  const oldRoute = props.src || getOldRoute(locationPathname);
  const iframeRef = useRef({ contentWindow: window, contentDocument: window });
  const actionRef = useRef<{ timer?: NodeJS.Timeout }>({});
  const [iframeHeight, triggerObserver] = useIframeHeight(iframeRef);

  const url = useMemo(() => {
    if (oldRoute) {
      const [oldPathname, oldSearch] = oldRoute.split('?');
      const search = qs.stringify({ ...query, ...qs.parse(oldSearch), winSize, _i_: 1 });
      return `${/^https?:\/\//.test(oldPathname) ? '' : '/'}${oldPathname}?${search}${hash}`;
    }
    return '';
  }, [oldRoute, winSize]);

  const handleIframeLoad = () => {
    const iframeDoc = triggerObserver();
    fixStyles(iframeDoc);
    actionRef.current.timer = setTimeout(() => {
      setShow(true);
    }, 100);
  };

  const rootCls = classNames(styles.screenBox, {
    [styles['screenBox-hidden']]: !show,
  });

  useEffect(() => {
    clearTimeout(actionRef.current.timer);
    if (!url) return;
    setShow(false);
  }, [url]);

  return url ? (
    <Spin spinning={!show}>
      <div className={rootCls}>
        <div className={styles.scrollX}>
          <iframe
            src={url}
            width='100%'
            style={{ minHeight: 'calc(100vh - 175px)' }}
            height={`${iframeHeight}px`}
            // scrolling="no"
            frameBorder='0'
            className={styles.iframe}
            onLoad={handleIframeLoad}
            ref={iframeRef as any}
          />
        </div>
      </div>
    </Spin>
  ) : (
    <>{props.children}</>
  );
};

export default Iframe;
